<?php
class OrderRecord extends TActiveRecord
{
	const TABLE='tbl_order';

	public $ID;
	public $Num;
	public $UserID;
	public $SFullName;
	public $SAddress;
	public $SCity;
	public $SCountryCode;
	public $SPostalCode;
	public $SEmail;
	public $SPhone;
	public $SPhone2;
	public $Subtotal;
	public $ShippingMethod;
	public $ShippingAmount;
	public $CouponCode;
	public $CouponAmount;
	public $RewardPointsRebate;
	public $TotalAmount;
	public $Currency;
	public $PaymentMethod;
	public $PaymentStatus;
	public $OrderStatus;
	public $IPAddress;
	public $Comments;
	public $AdminRemarks;
	public $InternalRemarks;
	public $CreateDate;
	public $ModifyDate;
	public $ModifyBy;
	
	public static $COLUMN_MAPPING=array
	(
		'order_id'=>'ID',
		'order_num'=>'Num',
		'user_id'=>'UserID',
		's_full_name'=>'SFullName',
		's_address'=>'SAddress',
		's_city'=>'SCity',
		's_country_code'=>'SCountryCode',
		's_postal_code'=>'SPostalCode',
		's_email'=>'SEmail',
		's_phone'=>'SPhone',
		's_phone2'=>'SPhone2',
		'subtotal'=>'Subtotal',
		'shipping_method'=>'ShippingMethod',
		'shipping_amount'=>'ShippingAmount',
		'coupon_code'=>'CouponCode',
		'coupon_amount'=>'CouponAmount',
		'reward_points_rebate'=>'RewardPointsRebate',
		'total_amount'=>'TotalAmount',
		'currency'=>'Currency',
		'payment_method'=>'PaymentMethod',
		'payment_status'=>'PaymentStatus',
		'order_status'=>'OrderStatus',
		'ip_address'=>'IPAddress',
		'comments'=>'Comments',
		'admin_remarks'=>'AdminRemarks',
		'internal_remarks'=>'InternalRemarks',
		'c_date'=>'CreateDate',
		'm_date'=>'ModifyDate',
		'm_by'=>'ModifyBy'
	);

	public static function finder($className=__CLASS__)
	{
		return parent::finder($className);
	}
	
	public function generateOrderNumber($prefix="",$length=6,$number=0)
	{
		$maxOrderNumber = 155001;
		if ($number<=0)
		{
			$criteria = new TActiveRecordCriteria;
			$criteria->Condition = "order_id = (select max(order_id) from tbl_order)";
			$items = self::finder()->findAll($criteria);
			foreach ($items as $item) 
			{				
				$maxOrderNumber = $item->Num;
			}
			
			if ($maxOrderNumber == 155001)
				$number = $maxOrderNumber;
			else
				$number = substr($maxOrderNumber,-6) + 1;
		}

		$orderNumber = $prefix . date("dmY",time()) . "-" . $number;
		return $orderNumber;
	}
	
	public function save()
	{
		if ($this->ID<=0)
		{
			$this->Num = $this->generateOrderNumber();
			$this->CreateDate = time();
		}
		$this->ModifyDate = time();
		$this->ModifyBy = Prado::getApplication()->User->ID;
		parent::save();
	}
}
?>